<template>
  <!-- <div> -->
  <!-- <van-nav-bar
      title="MateChat"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    /> -->
  <McLayout class="container">
    <McHeader
      :title="'MateChat'"
      :logoImg="'https://matechat.gitcode.com/logo.svg'"
    >
      <template #operationArea>
        <div class="operations">
          <i class="icon-helping"></i>
        </div>
      </template>
    </McHeader>
    <McLayoutContent
      v-if="startPage"
      style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 12px;
      "
    >
      <McIntroduction
        :logoImg="'https://matechat.gitcode.com/logo2x.svg'"
        :title="'MateChat'"
        :subTitle="'Hi，欢迎使用 MateChat'"
        :description="description"
      ></McIntroduction>
      <McPrompt
        :list="introPrompt.list"
        :direction="introPrompt.direction"
        class="intro-prompt"
        @itemClick="onSubmit($event.label)"
      ></McPrompt>
    </McLayoutContent>
    <McLayoutContent class="content-container" v-else>
      <template v-for="(msg, idx) in messages" :key="idx">
        <McBubble
          v-if="msg.from === 'user'"
          :content="msg.content"
          :align="'right'"
          :avatarConfig="{
            imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg',
          }"
        >
        </McBubble>
        <McBubble
          v-else
          :content="msg.content"
          :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/logo.svg' }"
        >
        </McBubble>
      </template>
    </McLayoutContent>
    <div class="shortcut" style="display: flex; align-items: center; gap: 8px">
      <McPrompt
        v-if="!startPage"
        :list="simplePrompt"
        :direction="'horizontal'"
        style="flex: 1"
        @itemClick="onSubmit($event.label)"
      ></McPrompt>
      <Button
        style="margin-left: auto"
        icon="add"
        shape="circle"
        title="新建对话"
        size="sm"
        @click="newConversation"
      />
    </div>
    <McLayoutSender>
      <McInput
        :value="inputValue"
        :maxLength="2000"
        @change="(e) => (inputValue = e)"
        @submit="onSubmit"
      >
        <template #extra>
          <div class="input-foot-wrapper">
            <div class="input-foot-left">
              <span v-for="(item, index) in inputFootIcons" :key="index">
                <i :class="item.icon"></i>
                {{ item.text }}
              </span>
              <span class="input-foot-dividing-line"></span>
              <span class="input-foot-maxlength"
                >{{ inputValue.length }}/2000</span
              >
            </div>
            <div class="input-foot-right">
              <Button
                icon="op-clearup"
                shape="round"
                :disabled="!inputValue"
                @click="inputValue = ''"
                >清空输入</Button
              >
            </div>
          </div>
        </template>
      </McInput>
    </McLayoutSender>
  </McLayout>
  <!-- </div> -->
</template>

    <!-- <div
      class="yaowenalls"
      v-for="item in commentdata.titlelist"
      :key="item.id"
    >
      <div>
        <img src="../assets/header.jpg" class="headersty" alt="" />
      </div>
      <div class="centerss">
        <div class="titles">{{ item.username }}</div>

        <div class="wanbaos">
          <span>{{ item.text }}</span>
        </div>

        <div class="badgesty">
          <van-badge :content="item.total"> </van-badge>
        </div>
      </div>
    </div> -->




<script setup>
import { ref, onMounted, defineProps, toRefs, reactive } from "vue";
import { gettui, getuserinfo, getcommentinfo } from "../api/getlogin";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { Button } from "vue-devui/button";
import "vue-devui/button/style.css";
import OpenAI from "openai";

const client = ref();

client.value = new OpenAI({
  apiKey: "sk-axdpuvgrogblivfptwuhamxicvsiecdutrbkcbtzxjcdubei", // 替换模型APIKey
  baseURL: "https://api.siliconflow.cn/v1", // 替换模型API地址
  dangerouslyAllowBrowser: true,
});

const router = useRouter();
const route = useRoute();
const store = useStore();
const list = defineProps({ title: String });
const commentdata = reactive({ commentlist: [], titlelist: [] });
let listgroup = reactive([]);
let titlename = ref("");
const getcommentinfos = async () => {
  const { data: res } = await getcommentinfo();
  commentdata.commentlist = res;

  // 创建一个对象来存储每个username对应的最后一条数据
  const usernameMap = {};

  // 遍历res，更新usernameMap
  res.forEach((item) => {
    usernameMap[item.username] = item;
  });
  const onClickLeft = () => history.back();
  // 将usernameMap的值赋给list
  const list = Object.values(usernameMap);

  // 如果需要将处理后的数据赋值给commentdata.commentlist，可以这样做
  // commentdata.commentlist = list;
  commentdata.titlelist = list;
  console.log(list);
};
const onClickLeft = () => history.back();

onMounted(async () => {
  //   console.log(route.query.id);
  titlename.value = route.query.id;
  const { data: res } = await gettui();
  res.forEach((e) => {
    listgroup.push(e);
  });
  // getuserinfos();
  getcommentinfos();
});
//AI生成
const description = [
  "MateChat 可以辅助研发人员编码、查询知识和相关作业信息、编写文档等。",
  "作为AI模型，MateChat 提供的答案可能不总是确定或准确的，但您的反馈可以帮助 MateChat 做的更好。",
];
const introPrompt = {
  direction: "horizontal",
  list: [
    {
      value: "quickSort",
      label: "帮我写一个快速排序",
      iconConfig: { name: "icon-info-o", color: "#5e7ce0" },
      desc: "使用 js 实现一个快速排序",
    },
    {
      value: "helpMd",
      label: "你可以帮我做些什么？",
      iconConfig: { name: "icon-star", color: "rgb(255, 215, 0)" },
      desc: "了解当前大模型可以帮你做的事",
    },
    {
      value: "bindProjectSpace",
      label: "怎么绑定项目空间",
      iconConfig: { name: "icon-priority", color: "#3ac295" },
      desc: "如何绑定云空间中的项目",
    },
  ],
};
const simplePrompt = [
  {
    value: "quickSort",
    iconConfig: { name: "icon-info-o", color: "#5e7ce0" },
    label: "帮我写一个快速排序",
  },
  {
    value: "helpMd",
    iconConfig: { name: "icon-star", color: "rgb(255, 215, 0)" },
    label: "你可以帮我做些什么？",
  },
];
const startPage = ref(true);
const inputValue = ref("");
const inputFootIcons = [
  { icon: "icon-at", text: "智能体" },
  { icon: "icon-standard", text: "词库" },
  { icon: "icon-add", text: "附件" },
];

const messages = ref([
  {
    from: "user",
    content: "你好",
  },
  {
    from: "model",
    content: "你好，我是 MateChat",
    id: "init-msg",
  },
]);

const newConversation = () => {
  startPage.value = true;
  messages.value = [];
};

const onSubmit = (evt) => {
  inputValue.value = "";
  startPage.value = false;
  messages.value.push({
    from: "user",
    content: evt,
    avatarConfig: { name: "user" },
  });

  fetchData(evt);
};
const fetchData = async (ques) => {
  messages.value.push({
    from: "model",
    content: "",
    avatarConfig: { name: "model" },
    id: "",
    loading: true,
  });
  if (!client.value) {
    console.error("OpenAI client is not initialized.");
    return;
  }
  const completion = await client.value.chat.completions.create({
    model: "deepseek-ai/DeepSeek-V2.5", // 替换官网案例提供的model名称
    messages: [{ role: "user", content: ques }],
    stream: true,
  });
  messages.value[messages.value.length - 1].loading = false;
  for await (const chunk of completion) {
    const content = chunk.choices[0]?.delta?.content || "";
    const chatId = chunk.id;
    messages.value[messages.value.length - 1].content += content;
    messages.value[messages.value.length - 1].id = chatId;
  }
};
</script>
 


<style scoped="less">
.container {
  width: 100vw;
  /* margin: 20px auto; */
  height: calc(100vh - 40px);
  /* padding: 3px; */
  gap: 8px;
  background: #fff;
  border: 1px solid #ddd;
  /* border-radius: 16px; */
  margin-top: 2px;
  /* transform: scale(1.5); */
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow: auto;
}

.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;

  .input-foot-left {
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      font-size: 12px;
      color: #252b3a;
      cursor: pointer;
    }

    .input-foot-dividing-line {
      width: 1px;
      height: 14px;
      background-color: #d7d8da;
    }

    .input-foot-maxlength {
      font-size: 12px;
      color: #71757f;
    }
  }

  .input-foot-right {
    & > *:not(:first-child) {
      margin-left: 8px;
    }
  }
}
</style>